<template>
  <div class="model-browser">
    <!-- 页面标题和操作栏 -->
    <div class="page-header">
      <div class="header-left">
        <h1>模型浏览</h1>
        <p>查看和管理所有机器学习模型</p>
      </div>
      <div class="header-right">
        <el-button type="primary" @click="showCreateDialog">
          <el-icon><Plus /></el-icon>
          新建模型
        </el-button>
        <el-button @click="refreshModels">
          <el-icon><Refresh /></el-icon>
          刷新
        </el-button>
      </div>
    </div>

    <!-- 搜索和筛选栏 -->
    <div class="filter-section">
      <el-card shadow="never">
        <div class="filter-row">
          <div class="filter-item">
            <el-input
              v-model="searchKeyword"
              placeholder="搜索模型名称或描述..."
              @keyup.enter="handleSearch"
              clearable
            >
              <template #prefix>
                <el-icon><Search /></el-icon>
              </template>
            </el-input>
          </div>
          <div class="filter-item">
            <el-select v-model="statusFilter" placeholder="状态筛选" @change="handleStatusFilter">
              <el-option label="全部" value="all" />
              <el-option label="草稿" value="draft" />
              <el-option label="训练中" value="training" />
              <el-option label="训练完成" value="trained" />
              <el-option label="已部署" value="deployed" />
              <el-option label="训练失败" value="failed" />
            </el-select>
          </div>
          <div class="filter-item">
            <el-select v-model="typeFilter" placeholder="类型筛选" @change="handleTypeFilter">
              <el-option label="全部" value="all" />
              <el-option label="用户流失预测" value="churn_prediction" />
              <el-option label="购买意向预测" value="purchase_prediction" />
              <el-option label="商品推荐系统" value="recommendation" />
              <el-option label="用户行为分群" value="user_segmentation" />
            </el-select>
          </div>
          <div class="filter-item">
            <el-select v-model="sortBy" placeholder="排序方式" @change="handleSort">
              <el-option label="更新时间(最新)" value="updateTime" />
              <el-option label="创建时间(最新)" value="createTime" />
              <el-option label="模型名称" value="name" />
              <el-option label="准确率(最高)" value="accuracy" />
            </el-select>
          </div>
        </div>
      </el-card>
    </div>

    <!-- 初始加载状态 -->
    <div v-if="!initialized" class="initial-loading">
      <el-skeleton :rows="5" animated />
    </div>

    <!-- 模型列表 -->
    <div class="models-grid" v-if="initialized">
      <!-- 空状态显示 -->
      <div v-if="!loading && filteredModels.length === 0" class="empty-state">
        <el-empty description="暂无模型数据">
          <el-button type="primary" @click="showCreateDialog">创建第一个模型</el-button>
        </el-empty>
      </div>

      <!-- 加载状态 -->
      <div v-if="loading" class="loading-state">
        <el-skeleton :rows="3" animated />
      </div>

      <!-- 模型卡片列表 -->
      <el-row :gutter="20" v-if="!loading && filteredModels.length > 0">
        <el-col
          v-for="model in filteredModels"
          :key="model.id"
          :xs="24"
          :sm="12"
          :md="8"
          :lg="6"
        >
          <el-card class="model-card" shadow="hover">
            <template #header>
              <div class="model-header">
                <div class="model-info">
                  <h3 class="model-name">{{ model.name }}</h3>
                  <el-tag :type="getStatusType(model.status)" size="small">
                    {{ getStatusText(model.status) }}
                  </el-tag>
                </div>
                <el-dropdown @command="handleModelCommand" trigger="click" @click.stop>
                  <el-button type="text">
                    <el-icon><MoreFilled /></el-icon>
                  </el-button>
                  <template #dropdown>
                    <el-dropdown-menu>
                      <el-dropdown-item :command="`train-${model.id}`">
                        <el-icon><VideoPlay /></el-icon>
                        训练模型
                      </el-dropdown-item>
                      <el-dropdown-item :command="`evaluate-${model.id}`">
                        <el-icon><DataAnalysis /></el-icon>
                        模型评估
                      </el-dropdown-item>
                      <el-dropdown-item :command="`deploy-${model.id}`" v-if="model.status === 'trained'">
                        <el-icon><Upload /></el-icon>
                        部署模型
                      </el-dropdown-item>
                      <el-dropdown-item :command="`export-${model.id}`">
                        <el-icon><Download /></el-icon>
                        导出模型
                      </el-dropdown-item>
                      <el-dropdown-item :command="`delete-${model.id}`" divided>
                        <el-icon><Delete /></el-icon>
                        删除模型
                      </el-dropdown-item>
                    </el-dropdown-menu>
                  </template>
                </el-dropdown>
              </div>
            </template>
            
            <div class="model-content" @click="viewModelDetail(model)" style="cursor: pointer;">
              <div class="model-description">
                <p>{{ model.description }}</p>
              </div>
              
              <div class="model-metrics">
                <div class="metric-item">
                  <span class="metric-label">类型</span>
                  <span class="metric-value">{{ model.model_type_display || getTypeText(model.model_type) }}</span>
                </div>
                <div class="metric-item">
                  <span class="metric-label">算法</span>
                  <span class="metric-value">{{ model.algorithm_display || model.algorithm }}</span>
                </div>
                <div class="metric-item">
                  <span class="metric-label">准确率</span>
                  <span class="metric-value">{{ model.accuracy ? (model.accuracy * 100).toFixed(2) + '%' : 'N/A' }}</span>
                </div>
                <div class="metric-item" v-if="model.precision">
                  <span class="metric-label">精确率</span>
                  <span class="metric-value">{{ (model.precision * 100).toFixed(2) + '%' }}</span>
                </div>
                <div class="metric-item" v-if="model.recall">
                  <span class="metric-label">召回率</span>
                  <span class="metric-value">{{ (model.recall * 100).toFixed(2) + '%' }}</span>
                </div>
                <div class="metric-item" v-if="model.f1_score">
                  <span class="metric-label">F1分数</span>
                  <span class="metric-value">{{ (model.f1_score * 100).toFixed(2) + '%' }}</span>
                </div>
              </div>
              
              <div class="model-footer">
                <div class="model-time">
                  <small>更新于 {{ formatDate(model.updated_at) }}</small>
                </div>
                <div class="model-version">
                  <el-tag size="small" type="info">v{{ model.version }}</el-tag>
                </div>
              </div>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>

    <!-- 分页 -->
    <div class="pagination-wrapper" v-if="!loading && filteredModels.length > 0">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[12, 24, 48, 96]"
        :total="totalModels"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 模型详情对话框 -->
    <el-dialog
      v-model="detailDialogVisible"
      title="模型详情"
      width="70%"
      class="model-detail-dialog"
    >
      <ModelDetail 
        v-if="currentModel"
        :model="currentModel"
        @train="handleTrain"
        @evaluate="handleEvaluate"
        @deploy="handleDeploy"
        @export="handleExport"
      />
    </el-dialog>

    <!-- 创建模型对话框 -->
    <el-dialog
      v-model="createDialogVisible"
      title="新建模型"
      width="50%"
    >
      <ModelCreator
        @save="handleCreateModel"
        @cancel="createDialogVisible = false"
      />
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  Plus, Refresh, Search, MoreFilled, VideoPlay, DataAnalysis,
  Upload, Download, Delete
} from '@element-plus/icons-vue'
import ModelDetail from './components/ModelDetail.vue'
import ModelCreator from './components/ModelCreator.vue'
import { getModelList, getModelDetail, createModel, deleteModel, startTraining, stopTraining } from '@/api/models'

// 路由实例
const router = useRouter()

// 响应式数据
const searchKeyword = ref('')
const statusFilter = ref('all')
const typeFilter = ref('all')
const sortBy = ref('updateTime')
const currentPage = ref(1)
const pageSize = ref(12)

const detailDialogVisible = ref(false)
const createDialogVisible = ref(false)
const currentModel = ref(null)
const loading = ref(false)
const initialized = ref(false)

// 模型列表数据
const models = ref([])
const totalCount = ref(0)

// 从后端加载模型列表
const loadModels = async () => {
  try {
    loading.value = true

    const params = {
      page: currentPage.value,
      page_size: pageSize.value,
      search: searchKeyword.value.trim(),
      status: statusFilter.value === 'all' ? '' : statusFilter.value,
      type: typeFilter.value === 'all' ? '' : typeFilter.value,
      sortBy: sortBy.value
    }

    // 移除空参数
    Object.keys(params).forEach(key => {
      if (params[key] === '' || params[key] === null || params[key] === undefined) {
        delete params[key]
      }
    })

    console.log('发送API请求，参数:', params)
    const response = await getModelList(params)
    console.log('API响应:', response)

    if (response && response.success) {
      models.value = response.data?.models || []
      totalCount.value = response.data?.pagination?.total_count || 0

      console.log('加载的模型数量:', models.value.length)
      console.log('模型数据:', models.value)

      if (models.value.length === 0) {
        ElMessage.info('暂无模型数据，请先在训练页面创建模型')
      } else {
        ElMessage.success(`成功加载 ${models.value.length} 个模型`)
      }
    } else {
      console.error('API响应失败:', response)
      ElMessage.error(response?.message || '加载模型列表失败')
    }
  } catch (error) {
    console.error('加载模型列表失败:', error)
    console.error('错误详情:', error.response?.data || error.message)

    if (error.response) {
      // 服务器响应了错误状态码
      ElMessage.error(`服务器错误: ${error.response.status} - ${error.response.data?.message || error.message}`)
    } else if (error.request) {
      // 请求发出但没有收到响应
      ElMessage.error('无法连接到服务器，请检查后端服务是否启动')
    } else {
      // 其他错误
      ElMessage.error(`请求失败: ${error.message}`)
    }
  } finally {
    loading.value = false
    initialized.value = true
  }
}

// 计算属性
const totalModels = computed(() => {
  return totalCount.value
})

const filteredModels = computed(() => {
  return Array.isArray(models.value) ? models.value : []
})

// 方法
const refreshModels = () => {
  loadModels()
}

const handleSearch = () => {
  currentPage.value = 1
  loadModels()
}

const handleStatusFilter = () => {
  currentPage.value = 1
  loadModels()
}

const handleTypeFilter = () => {
  currentPage.value = 1
  loadModels()
}

const handleSort = () => {
  currentPage.value = 1
  loadModels()
}

const handleSizeChange = (size) => {
  pageSize.value = size
  currentPage.value = 1
  loadModels()
}

const handleCurrentChange = (page) => {
  currentPage.value = page
  loadModels()
}

const viewModelDetail = async (model) => {
  try {
    const response = await getModelDetail(model.id)

    if (response && response.success) {
      currentModel.value = response.data
    } else {
      currentModel.value = model
    }

    detailDialogVisible.value = true
  } catch (error) {
    console.error('获取模型详情失败:', error)
    currentModel.value = model
    detailDialogVisible.value = true
  }
}

const showCreateDialog = () => {
  createDialogVisible.value = true
}

const handleModelCommand = (command) => {
  const [action, id] = command.split('-')
  const model = models.value.find(m => m.id === parseInt(id))

  switch (action) {
    case 'train':
      handleTrain(model)
      break
    case 'evaluate':
      handleEvaluate(model)
      break
    case 'deploy':
      handleDeploy(model)
      break
    case 'export':
      handleExport(model)
      break
    case 'delete':
      handleDelete(model)
      break
  }
}

const handleTrain = async (model) => {
  try {
    if (model.status === 'training') {
      await stopTraining(model.id)
      ElMessage.success('训练已停止')
    } else {
      await startTraining(model.id)
      ElMessage.success('训练已启动')
    }
    loadModels()
  } catch (error) {
    console.error('训练操作失败:', error)
    ElMessage.error('训练操作失败')
  }
}

const handleEvaluate = (model) => {
  router.push(`/models/evaluate/${model.id}`)
}

const handleDeploy = async (model) => {
  try {
    await ElMessageBox.confirm(`确定要部署模型 "${model.name}" 吗？`, '确认部署', {
      type: 'warning'
    })

    model.status = 'deployed'
    ElMessage.success('模型部署成功')
  } catch {
    // 用户取消
  }
}

const handleExport = (model) => {
  ElMessage.success(`正在导出模型 "${model.name}"...`)
}

const handleDelete = async (model) => {
  try {
    await ElMessageBox.confirm(`确定要删除模型 "${model.name}" 吗？此操作不可恢复！`, '确认删除', {
      type: 'error'
    })

    await deleteModel(model.id)
    ElMessage.success('模型删除成功')
    loadModels()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除模型失败:', error)
      ElMessage.error('删除模型失败')
    }
  }
}

const handleCreateModel = async (modelData) => {
  try {
    await createModel(modelData)
    createDialogVisible.value = false
    ElMessage.success('模型创建成功')
    loadModels()
  } catch (error) {
    console.error('创建模型失败:', error)
    ElMessage.error('创建模型失败')
  }
}

onMounted(() => {
  loadModels()
})

const getStatusType = (status) => {
  const types = {
    draft: 'info',
    training: 'warning',
    trained: 'success',
    deployed: 'primary',
    failed: 'danger'
  }
  return types[status] || 'info'
}

const getStatusText = (status) => {
  const texts = {
    draft: '草稿',
    training: '训练中',
    trained: '训练完成',
    deployed: '已部署',
    failed: '训练失败'
  }
  return texts[status] || '未知'
}

const getTypeText = (type) => {
  const texts = {
    churn_prediction: '用户流失预测',
    purchase_prediction: '购买意向预测',
    recommendation: '商品推荐系统',
    user_segmentation: '用户行为分群',
    price_optimization: '动态价格优化',
    inventory_forecast: '库存需求预测',
    fraud_detection: '欺诈行为检测',
    lifetime_value: '客户生命周期价值',
    sentiment_analysis: '用户评价情感分析',
    conversion_optimization: '转化率优化'
  }
  return texts[type] || type
}

const formatDate = (dateString) => {
  return new Date(dateString).toLocaleDateString()
}
</script>

<style scoped>
.model-browser {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: calc(100vh - 120px);
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.header-left h1 {
  margin: 0 0 5px 0;
  color: #303133;
  font-size: 24px;
  font-weight: 600;
}

.header-left p {
  margin: 0;
  color: #909399;
  font-size: 14px;
}

.header-right {
  display: flex;
  gap: 12px;
}

.filter-section {
  margin-bottom: 20px;
}

.filter-row {
  display: flex;
  gap: 16px;
  align-items: center;
  flex-wrap: wrap;
}

.filter-item {
  min-width: 200px;
}

.filter-item .el-input,
.filter-item .el-select {
  width: 100%;
}

.initial-loading,
.loading-state {
  padding: 40px;
}

.empty-state {
  text-align: center;
  padding: 60px 20px;
}

.models-grid {
  margin-bottom: 20px;
}

.model-card {
  margin-bottom: 20px;
  border-radius: 8px;
  transition: all 0.3s ease;
}

.model-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 8px 25px rgba(0, 0, 0, 0.1);
}

.model-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
}

.model-info {
  flex: 1;
}

.model-name {
  margin: 0 0 8px 0;
  font-size: 16px;
  font-weight: 600;
  color: #303133;
  line-height: 1.4;
}

.model-content {
  padding: 0;
}

.model-description {
  margin-bottom: 16px;
}

.model-description p {
  margin: 0;
  color: #606266;
  font-size: 14px;
  line-height: 1.5;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.model-metrics {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 8px;
  margin-bottom: 16px;
}

.metric-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 4px 0;
}

.metric-label {
  font-size: 12px;
  color: #909399;
}

.metric-value {
  font-size: 12px;
  color: #303133;
  font-weight: 500;
}

.model-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding-top: 12px;
  border-top: 1px solid #f0f0f0;
}

.model-time {
  color: #c0c4cc;
  font-size: 12px;
}

.pagination-wrapper {
  display: flex;
  justify-content: center;
  padding: 20px 0;
}

.model-detail-dialog {
  border-radius: 8px;
}

@media (max-width: 768px) {
  .model-browser {
    padding: 10px;
  }

  .page-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 16px;
  }

  .header-right {
    width: 100%;
    justify-content: flex-end;
  }

  .filter-row {
    flex-direction: column;
    align-items: stretch;
  }

  .filter-item {
    min-width: auto;
  }

  .model-metrics {
    grid-template-columns: 1fr;
  }
}
</style>
